﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Windows;
using System.Xml.Linq;
using DCClient.Views;
using ExcelReporting;
using Microsoft.Practices.Prism.Commands;
using OrgProperyDataSender;
using RegisterProvider;
using XMLTransformer;


namespace DCClient.ViewModels
{
    public class PropertyTableViewModel : DependencyObject
    {
        public readonly IRegister Register = new RegisterDataBaseConnector();

        private PropertyTableView _view;

        public PropertyTableViewModel(PropertyTableView linkView)
        {
            _view = linkView;
            var table = Register.RegisterTable;
            PropertyTable = table;
            PropertyTableView = table.AsDataView();
        }

        public static readonly DependencyProperty PropertyTableViewProperty = DependencyProperty.Register(
            "PropertyTableViewView", typeof (DataView), typeof (PropertyTableViewModel),
            new PropertyMetadata(default(DataView)));

        public DataView PropertyTableView
        {
            get { return (DataView) GetValue(PropertyTableViewProperty); }
            set { SetValue(PropertyTableViewProperty, value); }
        }

        public static readonly DependencyProperty PropertyTableProperty = DependencyProperty.Register(
            "PropertyTable", typeof (DataTable), typeof (PropertyTableViewModel),
            new PropertyMetadata(default(DataTable)));

        public DataTable PropertyTable
        {
            get { return (DataTable) GetValue(PropertyTableProperty); }
            set { SetValue(PropertyTableProperty, value); }
        }

        public DelegateCommand ExportToExcelCommand
        {
            get { return new DelegateCommand(ExportToExcel); }
        }

        public void ExportToExcel()
        {
            var excelDocument = new NPOIExcelDocumentConnector(Environment.CurrentDirectory + "\\Справочник товаров.xls");
            excelDocument[0, 0] = "Справочник товаров " + DateTime.Now;
            excelDocument.SetStyle(0, 0, 0, 10, new List<StyleModes> {StyleModes.Merged, StyleModes.Bold});
            excelDocument.SetStyle(2, Register.RegisterTable.Rows.Count + 2, 0, 1,
                new List<StyleModes>
                {
                    StyleModes.SimpleBorders,
                    StyleModes.CenterHorizontalAlignment,
                    StyleModes.TopVerticalAlignment
                }, true);
            excelDocument[2, 0] = "Идентификатор товара";
            excelDocument[2, 1] = "Цена";
            excelDocument.CopyDataTable(Register.RegisterTable, 3, 0);
            excelDocument.EndProcessing(true);
        }

        public DelegateCommand SaveCommand
        {
            get { return new DelegateCommand(Save); }
        }

        public void Save()
        {
            Register.ApplyChanges();
        }

        public DelegateCommand AddingCommand
        {
            get { return new DelegateCommand(Add); }
        }

        public void Add()
        {
            var propertyView = new PropertyView();
            propertyView.ShowDialog();

            try
            {
                var newRow = Register.RegisterTable.NewRow();
                newRow[RegisterFileConnector.IdentColumnName] = propertyView.Item.Name;
                newRow[RegisterFileConnector.PriceColumnName] = propertyView.Item.Price;
                Register.RegisterTable.Rows.Add(newRow);
            }
            catch (ConstraintException)
            {
                MessageBox.Show("Запись с таким идентификатором уже существует");
            }
        }

        public DelegateCommand DeletingCommand
        {
            get { return new DelegateCommand(Delete); }
        }

        public void Delete()
        {
            var propertyDeleteView = new PropertyDeleteView();
            propertyDeleteView.ShowDialog();

            var ident = propertyDeleteView.Item.Name;
            var rowsToDelete = Register.RegisterTable.AsEnumerable()
                .Where(row => row.RowState != DataRowState.Deleted)
                .Where(row => row.Field<string>("ident") == ident);
            if (!rowsToDelete.Any())
            {
                MessageBox.Show("Товар с данным идентификатором не найден");
            }
            else
            {
                foreach (var dataRow in rowsToDelete)
                {
                    dataRow.Delete();
                }
            }
        }

        public DelegateCommand CancelCommand
        {
            get { return new DelegateCommand(Cancel); }
        }

        public void Cancel()
        {
            var dialogResult = MessageBox.Show("Вы хотите закрыть приложение?", "Справочник товаров",
                MessageBoxButton.YesNo, MessageBoxImage.Information);
            if (dialogResult == MessageBoxResult.Yes)
            {
                _view.Close();
            }
        }

        private void Synchronizate()
        {
            var sendResult = OrgPropertyDataSender.PostChanges(Register.RegisterTable);
            MessageBox.Show(sendResult);
        }

        public DelegateCommand SynchrinizateCommand
        {
            get { return new DelegateCommand(Synchronizate); }
        }

        public DelegateCommand Importfromxmlcommand
        {
            get { return new DelegateCommand(Importfromxml); }
        }

        // 1) получить данные из файла (List<PropertyItem>)
        // 2) записать Prop4ertyItem в базу 

        private void Importfromxml()
        {
            const string TestFilesFolderPath = "C:/";
            const string filePath = TestFilesFolderPath + "PropertyItems-CountTest.xml";
            var xmlTransformer = new XmlTransformer();
            var propertyItems = xmlTransformer.Import(filePath);

            //writePropertyItemsToDB(propertyItems);
        }

        //public void ExportToXml(List<PropertyItem> items, string pathToXml)
        //{
        //    var xDoc = new XDocument(new XElement("PropertyItems"));
        //    foreach (var item in items)
        //    {
        //        xDoc.Element("PropertyItems").Add(new XElement("PropertyItem", new XElement("Ident", item.Ident), new XElement("Price", item.Price)));
        //    }
        //    xDoc.Save(pathToXml);
        //}

        //public DelegateCommand ExportToXmlCommand
        //    {
        //        get
        //        {
        //            return new DelegateCommand(ExportToXml);
        //        }
        //    }
        //}
    }
}
